package com.continuing.web.controller.beef;

import java.util.List;

import com.continuing.beef.service.BeefCommonService;
import com.continuing.beef.service.bill.IBillInfoService;
import com.continuing.beef.service.type.IBillTypeService;
import com.continuing.common.utils.StringUtils;
import com.continuing.framework.web.service.TokenService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.continuing.common.annotation.Log;
import com.continuing.common.core.controller.BaseController;
import com.continuing.common.core.domain.AjaxResult;
import com.continuing.common.enums.BusinessType;
import com.continuing.beef.domain.BillInfo;
import com.continuing.common.utils.poi.ExcelUtil;
import com.continuing.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;

/**
 * 账单信息Controller
 *
 * @author batata
 * @date 2021-09-26
 */
@RestController
@RequestMapping("/beef/bill")
public class BillInfoController extends BaseController {

    @Autowired
    private IBillInfoService billInfoService;

    @Autowired
    private BeefCommonService beefCommonService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IBillTypeService billTypeService;

    /**
     * 查询账单信息列表
     */
    @PreAuthorize("@ss.hasPermi('beef:bill:list')")
    @GetMapping("/list")
    public TableDataInfo list(BillInfo billInfo) {

        // 查询登录人公司下面的账单信息
        billInfo.setDeptIdFirmBill(
                beefCommonService.getFirmDeptIdByDeptId(getDeptId())
        );

        startPage();

        List<BillInfo> list = billInfoService.selectBillInfoList(billInfo);
        return getDataTable(list);
    }

    /**
     * 导出账单信息列表
     */
    @PreAuthorize("@ss.hasPermi('beef:bill:export')")
    @Log(title = "账单信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(BillInfo billInfo) {
        List<BillInfo> list = billInfoService.selectBillInfoList(billInfo);
        ExcelUtil<BillInfo> util = new ExcelUtil<BillInfo>(BillInfo.class);
        return util.exportExcel(list, "账单信息数据");
    }

    /**
     * 获取账单信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('beef:bill:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(billInfoService.selectBillInfoById(id));
    }

    /**
     * 新增账单信息
     */
    @PreAuthorize("@ss.hasPermi('beef:bill:add')")
    @Log(title = "账单信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BillInfo billInfo, HttpServletRequest request) {

        AjaxResult ajaxResult = verifyBillInfo(billInfo);
        if (!ajaxResult.get("code").toString().equals("200")) {
            return ajaxResult;
        }

        billInfo.setUserIdClient(billInfo.getClientUser());
        billInfo.setUserNickNameClient(
                beefCommonService.getNickNameByUserId(
                        billInfo.getClientUser()
                )
        );

        billInfo.setTypeId(billInfo.getBillTypeData());
        billInfo.setTypeExplain(
                billTypeService.selectBillTypeByTypeId(
                        billInfo.getBillTypeData()
                ).getTypeExplain()
        );

        // 设置账单状态   start
        setBillStatus(billInfo);
        // 设置账单状态   end

        return toAjax(billInfoService.insertBillInfo(billInfo, tokenService.getLoginUser(request)));
    }

    /**
     * 修改账单信息
     */
    @PreAuthorize("@ss.hasPermi('beef:bill:edit')")
    @Log(title = "账单信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BillInfo billInfo, HttpServletRequest request) {

        AjaxResult ajaxResult = verifyBillInfo(billInfo);
        if (!ajaxResult.get("code").toString().equals("200")) {
            return ajaxResult;
        }

        // 设置账单状态   start
        setBillStatus(billInfo);
        // 设置账单状态   end

        return toAjax(billInfoService.updateBillInfo(billInfo, tokenService.getLoginUser(request)));
    }

    /**
     * 验证接收到的信息
     *
     * @param billInfo /
     * @return /
     */
    public AjaxResult verifyBillInfo(BillInfo billInfo) {
        if (StringUtils.isEmpty(billInfo.getBillTypeData())) {
            return AjaxResult.error("请选择账单类型。");
        } else if (billInfo.getClientUser() == null) {
            return AjaxResult.error("请选择账单所属客户。");
        } else if (billInfo.getSum() == null) {
            return AjaxResult.error("金额不能为空！");
        } else if (billInfoService.isExceed(billInfo.getSum(), billInfo.getSumDiscount(), billInfo.getSumPayment())) {
            return AjaxResult.error("优惠金额与付款金额的和大于账单金额");
        }
        return AjaxResult.success();
    }


    /**
     * 删除账单信息
     */
    @PreAuthorize("@ss.hasPermi('beef:bill:remove')")
    @Log(title = "账单信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(billInfoService.deleteBillInfoByIds(ids));
    }


    /**
     * 设置账单的状态
     *
     * @param billInfo 原有信息
     * @return /
     */
    private BillInfo setBillStatus(BillInfo billInfo) {

        Integer compareStatus = beefCommonService.compareSum(
                billInfo.getSum(),
                billInfo.getSumDiscount(),
                billInfo.getSumPayment()
        );

        if (compareStatus == 0) {
            billInfo.setStatusBill(1);
        }

        return billInfo;
    }

}
